package admin

import (
	"blogs/models"
	"blogs/utils"
	beego "github.com/beego/beego/v2/server/web"
)

// Operations about object
type NavController struct {
	beego.Controller
}

// @Title Create
// @Description 添加文章
// @Param	query		Title 	string	true		"The object content"
// @Success 200 {string}
// @Failure 403 body is empty
// @router / [post]
func (o *NavController) Post() {
	title := o.GetString("Title")
	link := o.GetString("Link")
	nav := models.Nav{}
	nav.Title = title
	nav.Link = link
	nav.AddTime = int(utils.GetUnix())

	err := utils.DB.Create(&nav).Error
	if err != nil {
		o.Data["json"] = map[string]interface{}{
			"msg":  "创建错误",
			"data": "创建错误",
			"code": false,
		}
		o.ServeJSON()
		return
	}
	o.Data["json"] = map[string]interface{}{
		"msg":  "添加成功",
		"data": "添加成功",
		"code": true,
	}
	o.ServeJSON()

}

// @Title GetAll
// @Description 查询所有文章
// @Success 200 {object} models.Article
// @Failure 403 :objectId is empty
// @router / [get]
func (o *NavController) GetAll() {

	nav := []models.Nav{}
	utils.DB.Find(&nav)

	o.Data["json"] = map[string]interface{}{
		"msg":  "查询成功",
		"data": nav,
		"code": false,
	}
	o.ServeJSON()
}

// @Title Update
// @Description 更新导航
// @Param	Id		query 	string	true		"The Id you want to update"
// @Success 200 Id
// @Failure 403 Id
// @router / [put]
func (o *NavController) Put() {

	// 接收参数
	id := o.GetString("Id")
	title := o.GetString("Title")
	link := o.GetString("Link")

	// 更新数据
	navs := []models.Nav{}
	utils.DB.Where("id=?", id).Find(&navs)
	if len(navs) > 0 {
		navs[0].Title = title
		navs[0].Link = link
		utils.DB.Save(&navs)
		o.Data["json"] = map[string]interface{}{
			"msg":  "更新成功",
			"data": "更新成功",
			"code": true,
		}
		o.ServeJSON()
		return
	}
	o.Data["json"] = map[string]interface{}{
		"msg":  "更新失败",
		"data": "更新失败",
		"code": false,
	}
	o.ServeJSON()
}

// @Title Delete
// @Description 删除文章
// @Param	Id		query 	string	true		"The Id you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 objectId is empty
// @router / [delete]
func (o *NavController) Delete() {
	objectId := o.GetString("Id")
	article := []models.Nav{}
	err := utils.DB.Where("id=?", objectId).Delete(&article).Error
	if err != nil {
		o.Data["json"] = map[string]interface{}{
			"msg":  "删除失败",
			"data": "删除失败",
			"code": false,
		}
		o.ServeJSON()
		return
	}
	o.Data["json"] = map[string]interface{}{
		"msg":  "删除成功",
		"data": "删除成功",
		"code": true,
	}
	o.ServeJSON()

}
